package servlet;

import model.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@WebServlet("/releaseNews")
public class ReleaseNews extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        Guser currentUser = (Guser) session.getAttribute("gcurrentUser");
        Integer guid = currentUser.guid;
        LocalDate date = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyy-MM-dd");
        String day = date.format(formatter);
        PrintWriter out = resp.getWriter();
        if (guid == null) {
            out.print("<script language='javascript'>alert('Wrong password. Login again!!'");
            return;
        }
        String atitle = req.getParameter("atitle");
        String acontents = req.getParameter("acontents");

        News news;
        try {
            news = sava(guid, atitle, acontents,day);
            resp.sendRedirect("/");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }

    }

    public static News sava(Integer guid, String atitle,String acontents,String day) throws SQLException {
        try (Connection c = DBUtil.getConnection()) {
            String sql = "INSERT INTO admin(guid,atitle,acontents,day) VALUES(?,?,?,?)";
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                s.setInt(1, guid);
                s.setString(2, atitle);
                s.setString(3, acontents);
                s.setString(4,day);
                s.executeUpdate();

            }
        }
        return null;
    }
}


